package com.applink.sell_proof;

import java.util.Date;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.applink.sell_proof.api.DataHelper;
import com.applink.sell_proof.api.DataResult;
import com.applink.sell_proof.api.Methods;
import com.applink.sell_proof.constant.Constant;
import com.applink.sell_proof.database.table.CountryDBHelper;
import com.applink.sell_proof.database.table.CustomerSupportHelper;
import com.applink.sell_proof.database.table.RedeemDBHelper;
import com.applink.sell_proof.model.Country;
import com.applink.sell_proof.model.Redeem;
import com.applink.sell_proof.model.UserProfile;

public class RedeemEdit extends BaseActionBarActivity implements Observer, OnClickListener {

	private static final String	TAG	= "RedeemDetail";
	private Redeem				mRedeem;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.redeem_edit);
		setTitle("Redeem Detail");
		
		
		Spanned country = Html.fromHtml(String.format("%s<font color='#ff0000'>*</font>", getString(R.string.country)));
		((TextView)findViewById(R.id.country_label)).setText(country);
		
		Spanned first_name = Html.fromHtml(String.format("%s<font color='#ff0000'>*</font>", getString(R.string.firstname)));
		((TextView)findViewById(R.id.first_name_label)).setText(first_name);
		
		Spanned last_name = Html.fromHtml(String.format("%s<font color='#ff0000'>*</font>", getString(R.string.lastname)));
		((TextView)findViewById(R.id.last_name_label)).setText(last_name);
		
		Spanned mobile = Html.fromHtml(String.format("%s<font color='#ff0000'>*</font>", getString(R.string.contact_phone)));
		((TextView)findViewById(R.id.phone_label)).setText(mobile);
		
		Spanned email = Html.fromHtml(String.format("%s<font color='#ff0000'>*</font>", getString(R.string.contact_email)));
		((TextView)findViewById(R.id.email_label)).setText(email);
		
		Spanned postal = Html.fromHtml(String.format("%s<font color='#ff0000'>*</font>", getString(R.string.postal_code)));
		((TextView)findViewById(R.id.postalcode_label)).setText(postal);
		
		Spanned street = Html.fromHtml(String.format("%s<font color='#ff0000'>*</font>", getString(R.string.str_name)));
		((TextView)findViewById(R.id.street_name_label)).setText(street);
		
		Spanned building = Html.fromHtml(String.format("%s<font color='#ff0000'>*</font>", getString(R.string.build_name)));
		((TextView)findViewById(R.id.building_name_label)).setText(building);
		
		Spanned unit = Html.fromHtml(String.format("%s<font color='#ff0000'>*</font>", getString(R.string.unit)));
		((TextView)findViewById(R.id.unit_name_label)).setText(unit);
		

		DataHelper.getInstance().addObserver(this);
		mRedeem = (Redeem) getIntent().getSerializableExtra(Constant.INTENT_REDEEM_DETAIL);

		((TextView) findViewById(R.id.program_name)).setText(mRedeem.getProgramName());
		String startDate = DateFormat.getDateFormat(this).format(new Date(mRedeem.getStartdate()));
		String endDate = DateFormat.getDateFormat(this).format(new Date(mRedeem.getEnddate()));
		((TextView) findViewById(R.id.tier_qualify)).setText(String.format("%s - %s", startDate, endDate));
		((TextView) findViewById(R.id.tier_product)).setText(mRedeem.getProduct());

		((EditText) findViewById(R.id.first_name)).addTextChangedListener(new RedeemTextWatcher(R.id.first_name));
		((EditText) findViewById(R.id.last_name)).addTextChangedListener(new RedeemTextWatcher(R.id.last_name));
		((EditText) findViewById(R.id.mobile_profile)).addTextChangedListener(new RedeemTextWatcher(R.id.mobile_profile));
		((EditText) findViewById(R.id.email_profile)).addTextChangedListener(new RedeemTextWatcher(R.id.email_profile));
		((EditText) findViewById(R.id.street_name_profile)).addTextChangedListener(new RedeemTextWatcher(R.id.street_name_profile));
		((EditText) findViewById(R.id.building_name_profile)).addTextChangedListener(new RedeemTextWatcher(R.id.building_name_profile));
		((EditText) findViewById(R.id.unit_profile)).addTextChangedListener(new RedeemTextWatcher(R.id.unit_profile));
		((EditText) findViewById(R.id.postal_code_profile)).addTextChangedListener(new RedeemTextWatcher(R.id.postal_code_profile));

		buildProfileContent();

		/**
		 * country
		 */
		List<Country> countries = CountryDBHelper.getAllCountry();
		if (countries != null) {
			initCountry(countries, (Spinner) findViewById(R.id.country_profile));
		} else {
			DataHelper.getInstance().getAllCountry();
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getSupportMenuInflater();
		inflater.inflate(R.menu.menu_redeem, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Spinner productSpinner = (Spinner) findViewById(R.id.country_profile);
		long country_id = ((Country) productSpinner.getSelectedItem()).getCode();
		String postalCode = ((Country) productSpinner.getSelectedItem()).getPostalCode();
		mRedeem.setPostalCode(postalCode);
		mRedeem.setCountryId(country_id);
		switch (item.getItemId()) {
		case R.id.save_redeem:
			if (checkValidate(mRedeem)) {
				RedeemDBHelper.createRedeem(mRedeem);
				DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case Dialog.BUTTON_NEGATIVE:
							dialog.dismiss();
							break;
						default:
							break;
						}
					}
				};
				showAlertDialog(listener, "Save Redeem", "Close", null,getString(R.string.msg_redeem_save_successful), true);
			}
			return true;
		case R.id.submit_redeem:
			clearErrorCheck();
			if (checkValidate(mRedeem)) {
				DataHelper.getInstance().saveRedeem(mRedeem);
				showProgressDialog(true);
			}
			return true;
		default:
			return false;
		}
	}

	private void buildProfileContent() {
		if (mRedeem.getFirstName() != null) {
			((EditText) findViewById(R.id.first_name)).setText(mRedeem.getFirstName());
			((EditText) findViewById(R.id.last_name)).setText(mRedeem.getLastName());
			((EditText) findViewById(R.id.mobile_profile)).setText(mRedeem.getMobile());
			((EditText) findViewById(R.id.email_profile)).setText(mRedeem.getEmail());
			((EditText) findViewById(R.id.street_name_profile)).setText(mRedeem.getStreet());
			((EditText) findViewById(R.id.building_name_profile)).setText(mRedeem.getBuilding());
			((EditText) findViewById(R.id.unit_profile)).setText(mRedeem.getUnit());
			((EditText) findViewById(R.id.postal_code_profile)).setText(mRedeem.getPostalCode());
		} else {
			UserProfile user = CustomerSupportHelper.GetUserProfile();
			if (user != null) {
				((EditText) findViewById(R.id.first_name)).setText(user.getFirstname());
				((EditText) findViewById(R.id.last_name)).setText(user.getLastname());
				((EditText) findViewById(R.id.mobile_profile)).setText(user.getMobileNo());
				((EditText) findViewById(R.id.email_profile)).setText(user.getEmail());
				((EditText) findViewById(R.id.street_name_profile)).setText(user.getDeliAddStreetName());
				((EditText) findViewById(R.id.building_name_profile)).setText(user.getDeliAddBuildName());
				((EditText) findViewById(R.id.unit_profile)).setText(user.getDeliAddUnit());
				((EditText) findViewById(R.id.postal_code_profile)).setText(user.getDeliAddPostalCode());
			}
		}
	}

	@Override
	public void update(Observable observable, Object data) {
		if (data == null)
			return;
		DataResult result = (DataResult) data;
		if (result.getMethodName() == Methods.getAllCountry) {
			hideProgressDialog();
			List<Country> countries = CountryDBHelper.getAllCountry();
			if (countries != null) {
				initCountry(countries, (Spinner) findViewById(R.id.country_profile));
			} else {
				Log.e(TAG, "no country");
			}
		} else if (result.getMethodName() == Methods.saveRedeem) {
			hideProgressDialog();
			if (result.getErrorCode() == null) {
				DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case Dialog.BUTTON_NEGATIVE:
							dialog.dismiss();
							break;
						default:
							break;
						}
					}
				};
				showAlertDialog(listener, "Redeem", "Close", null,getString(R.string.msg_redeem_submit_successful), true);
			} else {
				DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case Dialog.BUTTON_NEGATIVE:
							dialog.dismiss();
							break;
						default:
							break;
						}
					}
				};
				showAlertDialog(listener, "Redeem", "Close", null, getString(R.string.msg_redeem_submit_failed), true);
			}
		}
	}

	protected void initCountry(List<Country> countries, Spinner spinner) {
		if (countries != null) {
			ArrayAdapter<Country> adapter_country = new ArrayAdapter<Country>(this, R.layout.spinner_item, countries);
			spinner.setAdapter(adapter_country);

			if (mRedeem != null) {
				for (int i = 0; i < countries.size(); i++) {
					if (mRedeem.getCountryId() == countries.get(i).getCode()) {
						spinner.setSelection(i);
						mRedeem.setPostalCode(countries.get(i).getPostalCode());
					}
				}
			}
		}
	}

	private boolean checkValidate(Redeem redeem) {

		String mailRegex = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
		DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case Dialog.BUTTON_NEGATIVE:
					dialog.dismiss();
					break;
				default:
					break;
				}
			}
		};
		boolean validated = true;
		if (redeem.getFirstName() == null || redeem.getFirstName().trim().length() == 0) {
			((TextView) findViewById(R.id.firstname_error)).setVisibility(View.VISIBLE);
			validated = false;
		} 
		if (redeem.getLastName() == null || redeem.getLastName().trim().length() == 0) {
			((TextView) findViewById(R.id.lastname_error)).setVisibility(View.VISIBLE);
			validated = false;
		} 
		if (redeem.getMobile() == null || redeem.getMobile().trim().length() == 0) {
			((TextView) findViewById(R.id.phone_error)).setVisibility(View.VISIBLE);
			validated = false;
		} 
		if (redeem.getEmail() == null || redeem.getEmail().trim().length() == 0) {
			((TextView) findViewById(R.id.email_error)).setVisibility(View.VISIBLE);
			validated = false;
		} 
		if (redeem.getEmail().matches(mailRegex) == false) {
			((TextView) findViewById(R.id.email_error)).setText(getString(R.string.error_email_invalid));
			((TextView) findViewById(R.id.email_error)).setVisibility(View.VISIBLE);
			validated = false;
		} 
		if (redeem.getPostalCode() == null || redeem.getPostalCode().trim().length() == 0) {
			((TextView) findViewById(R.id.postal_code_error)).setVisibility(View.VISIBLE);
			validated = false;
		} if (redeem.getStreet() == null || redeem.getStreet().trim().length() == 0) {
			((TextView) findViewById(R.id.street_error)).setVisibility(View.VISIBLE);
			validated = false;
		} if (redeem.getBuilding() == null || redeem.getBuilding().trim().length() == 0) {
			((TextView) findViewById(R.id.building_error)).setVisibility(View.VISIBLE);
			validated = false;
		} if (redeem.getUnit() == null || redeem.getUnit().trim().length() == 0) {
			((TextView) findViewById(R.id.unit_error)).setVisibility(View.VISIBLE);
			validated = false;
		}
		
		if(validated == false) {
			showAlertDialog(listener, "Submit Redeem", "Close", null, getString(R.string.error_create_deal_miss_field), true);
		}

		return validated;
	}

	private class RedeemTextWatcher implements TextWatcher {

		private int	_EditTextId;

		public RedeemTextWatcher(int editTextId) {
			super();
			_EditTextId = editTextId;
		}

		@Override
		public void afterTextChanged(Editable s) {
			switch (_EditTextId) {
			case R.id.first_name:
				mRedeem.setFirstName(s.toString());
				break;
			case R.id.last_name:
				mRedeem.setLastName(s.toString());
				break;
			case R.id.mobile_profile:
				mRedeem.setMobile(s.toString());
				break;
			case R.id.email_profile:
				mRedeem.setEmail(s.toString());
				break;
			case R.id.street_name_profile:
				mRedeem.setStreet(s.toString());
				break;
			case R.id.building_name_profile:
				mRedeem.setBuilding(s.toString());
				break;
			case R.id.unit_profile:
				mRedeem.setUnit(s.toString());
			case R.id.postal_code_profile:
				mRedeem.setPostalCode(s.toString());
				break;
			default:
				break;
			}

		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {

		}

	}

	private void clearErrorCheck() {
		((TextView) findViewById(R.id.firstname_error)).setVisibility(View.GONE);
		((TextView) findViewById(R.id.lastname_error)).setVisibility(View.GONE);
		((TextView) findViewById(R.id.phone_error)).setVisibility(View.GONE);
		((TextView) findViewById(R.id.email_error)).setVisibility(View.GONE);
		((TextView) findViewById(R.id.postal_code_error)).setVisibility(View.GONE);
		((TextView) findViewById(R.id.street_error)).setVisibility(View.GONE);
		((TextView) findViewById(R.id.building_error)).setVisibility(View.GONE);
		((TextView) findViewById(R.id.unit_error)).setVisibility(View.GONE);

	}
}
